import {
	baseUrl
} from './env'
import { Dialog,Toast} from 'vant';
import {setStore, getStore, getDefault} from '@/assets/config/mUtils';
import md5 from 'js-md5';
export default async(url = '', data = {}, type = 'GET', method = 'fetch',uploadUrl,file,clock,look) => {
  if(!navigator.onLine){
    Toast.clear();
      Dialog.alert({
        title: '',
        message: '网络中断,请检查网络！'
      });
    return new Promise(() => {})
  }

	type = type.toUpperCase();
	if(uploadUrl){
	  url = url;
  }else{
		var checkTime = new Date().getTime().toString();
		if(getStore('user_id')){
			url = baseUrl + url+'?app_userId='+getStore('user_id')+'&CHECK_TIME='+ checkTime+'&CHECK_SIGN='+ md5(getStore('user_id') + checkTime + "3a28fba00c015e0df7f88556c91cb7fc");
		}else{
			url = baseUrl + url;
		}
    
  }

  if (type == 'GET') {
		let dataStr = ''; //数据拼接字符串
		Object.keys(data).forEach(key => {
			dataStr += key + '=' + data[key] + '&';
		})

		if (dataStr !== '') {
			dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
			url = url + '&' + dataStr;
		}
	}
  if (window.fetch && method == 'fetch') {
		let requestConfig = {
			credentials: 'include',
			method: type,
			headers: {
				'Accept': 'application/json',
				'Content-Type': 'application/json'
			},
			mode: "cors",
			cache: "force-cache"
		}

		if (type == 'POST') {
			Object.defineProperty(requestConfig, 'body', {
				value: JSON.stringify(data)
			})
		}

		try {
			const response = await fetch(url, requestConfig);
      if(file){
        var responseJson = await response.blob();
      }else {
        var responseJson = await response.json();
      }
			return responseJson
		} catch (error) {
			throw new Error(error)
		}
	} else {
		return new Promise((resolve, reject) => {
      let urlEncoded = (data) => {
        if (typeof data == 'string') return encodeURIComponent(data);
        let params = [];
        for (let k in data) {
          if (!data.hasOwnProperty(k)) return;
          let v = data[k];
          if (typeof v == 'string') v = encodeURIComponent(v);
          if (v == undefined) v = '';
          params.push(`${encodeURIComponent(k)}=${v}`);
        }
        return params.join('&');
      }
			let requestObj;
			if (window.XMLHttpRequest) {
				requestObj = new XMLHttpRequest();
			} else {
				requestObj = new ActiveXObject;
			}

			let sendData = '';
			if (type == 'POST') {
				if(!file&&!clock){
					sendData =urlEncoded(data);
				}else if(!file&&clock){
          sendData =JSON.stringify(data);
        }else{
					sendData =data;

				}

			}
      // console.log(sendData,type,url);
      requestObj.open(type, url, true);
			if(!file&&!clock){
				requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			}else if(!file&&clock){
        requestObj.setRequestHeader("Content-type", "application/json");
      }
			// requestObj.setRequestHeader("Content-type", "multipart/form-data;charset=utf-8");
			requestObj.send(sendData);

			requestObj.onreadystatechange = () => {
				if (requestObj.readyState == 4) {
					if (requestObj.status == 200) {
						let obj = requestObj.response;
            // if(typeof obj !== 'object'&&look){
            //   var blob= new Blob();
            //   obj = requestObj.response;
            //   resolve(blob)
            // }
						if (typeof obj !== 'object') {
              obj = JSON.parse(obj);
						}
						resolve(obj)
					} else if(requestObj.status == 302){
            let obj = requestObj.response;
            if (typeof obj !== 'object') {
              obj = JSON.parse(obj);
            }
            resolve(obj)
          }else {
						reject(requestObj)
					}
				}
			}
		})
	}
}
